package com.logansoft.zhxypkoa.config;

import javax.servlet.Filter;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.ShallowEtagHeaderFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.logansoft.zhxypkoa.filter.JwtAuthenticationTokenFilter;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

	/*
	 * @Override public void addCorsMappings(CorsRegistry registry) {
	 * log.debug("设置跨域");
	 * registry.addMapping("/**").allowedHeaders("*").allowedMethods("*").
	 * allowedOrigins("*"); }
	 */

	// 注册自定义拦截器
	@Bean
	public FilterRegistrationBean<JwtAuthenticationTokenFilter> JwtAuthenticationTokenFilterRegistration() {
		FilterRegistrationBean<JwtAuthenticationTokenFilter> registration = new FilterRegistrationBean<JwtAuthenticationTokenFilter>();
		registration.setFilter(getJwtAuthenticationTokenFilter());
		registration.addUrlPatterns("/api/*");
		registration.addInitParameter("paramName", "paramValue");
		registration.setName("JwtAuthenticationTokenFilter");
		registration.setOrder(1);
		return registration;
	}

	@Bean
	public JwtAuthenticationTokenFilter getJwtAuthenticationTokenFilter() {
		// TODO Auto-generated method stub
		return new JwtAuthenticationTokenFilter();
	}

	// 因为 rest 导致资源文件返回 404
	// 重载方法添加自定义资源文件路径, 访问路径为 /static/**
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// TODO Auto-generated method stub
		registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
		WebMvcConfigurer.super.addResourceHandlers(registry);
	}

	// 注册 spring 提供的 etag 拦截器
	/*@Bean
	public FilterRegistrationBean<Filter> shallowEtagHeaderFilterRegistration() {
		FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<Filter>();
		registration.setFilter(getShallowEtagHeaderFilter());
		registration.addUrlPatterns("/*");
		registration.addInitParameter("paramName", "paramValue");
		registration.setName("ShallowEtagHeaderFilter");
		registration.setOrder(2);
		return registration;
	}*/
	
	@Bean
	public Filter getShallowEtagHeaderFilter() {
		return new ShallowEtagHeaderFilter();
	}
}
